import moment from 'moment'

import { TRADE_CHART_ACTION } from '../reducers/tradeChartReducer'
import { WS_SEND_DATA } from '../middleware/ws'

import { getHistoryKLine } from '../../api/klineApi'
import storageUtils from '../../utils/storageUtils'
import { formatValue } from '../../utils/dataUtils'

export const K_INTERVAL_REAL_TIME = 'real_time'
export const K_INTERVAL_ONE_MINUTE = 'one_minute'
export const K_INTERVAL_THREE_MINUTES = 'three_minutes'
export const K_INTERVAL_FIVE_MINUTES = 'five_minutes'
export const K_INTERVAL_FIFTEEN_MINUTES = 'fifteen_minutes'
export const K_INTERVAL_THIRTY_MINUTES = 'thirty_minutes'
export const K_INTERVAL_ONE_HOUR = 'one_hour'
export const K_INTERVAL_TWO_HOURS = 'two_hours'
export const K_INTERVAL_FOUR_HOURS = 'four_hours'
export const K_INTERVAL_SIX_HOURS = 'six_hours'
export const K_INTERVAL_TWELVE_HOURS = 'twelve_hours'
export const K_INTERVAL_ONE_DAY = 'one_day'
export const K_INTERVAL_ONE_WEEK = 'one_week'
export const K_INTERVAL_ONE_MONTH = 'one_month'

export const STOCK_CHART_TRADING_VIEW = 'trading_view'
export const STOCK_CHART_ORIGINAL_VIEW = 'original_view'

/**
 * 设置图表周期
 * @param interval
 * @returns {{data: {currentInterval: *}, type: string}}
 */
export function setChartInterval (interval) {
  storageUtils.saveValue(storageUtils.K_LINE_INTERVAL, interval)
  return {
    type: TRADE_CHART_ACTION,
    data: {
      currentInterval: interval
    }
  }
}

/**
 * 设置行情图表类型
 * @param type
 * @returns {{data: {stockChartType: *}, type: string}}
 */
export function setStockChartType (type) {
  return {
    type: TRADE_CHART_ACTION,
    data: {
      stockChartType: type
    }
  }
}

/**
 * 获取k线历史数据
 */
export function getHistoryKLineData (symbolInfo, resolution, from, to, onHistoryCallback, onErrorCallback) {
  let interval = resolution
  if (/^[\d]+$/.test(interval)) {
    if ((+resolution) >= 60) {
      const hours = (+resolution) / 60
      if (hours === 1) {
        interval = 'H'
      } else {
        interval = `${hours}H`
      }
    }
  }
  getHistoryKLine(symbolInfo.ticker, to, interval)
    .then((result) => {
      const klineDataList = []
      const dataList = result || []
      const isInverse = symbolInfo.isInverse
      dataList.forEach(data => {
        const timestamp = data.BeginTime * 1000
        klineDataList.push({
          time: timestamp, close: +data.ClosePrice,
          open: +data.OpenPrice, high: +data.HighestPrice,
          low: +data.LowestPrice, volume: +data.Volume,
          turnover: isInverse ? (+data.Volume * symbolInfo.volumeMultiple) / (+data.Turnover) * (+data.Volume) : +data.Turnover,
          timestamp
        })
      })
      onHistoryCallback(klineDataList, { noData: klineDataList.length === 0 })
    })
    .catch((error) => {
      onErrorCallback(error.errorMsg || 'error')
    })
}

/**
 * 订阅k线
 * @param contract
 * @param interval
 * @returns {function(...[*]=)}
 */
export function subscribeKLine (contract, interval) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '1',
            LocalNo: 4,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}_${interval}`,
            ResumeNo: -1
          }
        }
      })
    }
  }
}

/**
 * 取消订阅k线
 * @param contract
 * @param interval
 * @returns {function(...[*]=)}
 */
export function unsubscribeKLine (contract, interval) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '2',
            LocalNo: 4,
            TopicID: '2',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}_${interval}`,
            ResumeNo: -1
          }
        }
      })
    }
  }
}
